<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/10/25
// +----------------------------------------------------------------------

namespace app\common\services;

use app\common\facade\Arr;
use app\common\services\wechattemplate\UserTemplateService;
use library\tools\Data;
use think\Db;

/**
 *
 * Class UserService
 * @package app\common\services
 * @author feraner<feraner@163.com>
 * @date 2019/10/25
 */
class UserService
{

    protected $table = 'user';


    /**
     * 用户基本信息 + 扩展信息
     * @param       $userId
     * @param array $need   可取值： extend,userWallet,extendBus
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userInfo($userId, $need = [])
    {
        $userInfo = Db::name('user')
            ->where('id', $userId)
            ->field('last_login_ip,login_ip,password', true)
            ->find() ?: [];
        if (in_array('extend', $need)) {
            $userInfo['extend'] = Db::name('user_extend')
                ->where('user_id', $userId)
                ->find() ?: [];
        }
        if (in_array('extendBus', $need)) {
            $userInfo['extendBus'] = Db::name('user_extend_bus')
                ->where('user_id', $userId)
                ->find() ?: [];
        }
        if (in_array('userWallet', $need)) {
            $userInfo['extendUserWallet'] = Db::name('user_wallet')
                ->where('user_id', $userId)
                ->find() ?: [];
        }
        return $userInfo;
    }


    /**
     * 自动登录流程 -- 更新/新增用户
     *
     * @param $userInfo
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function updateUser($userInfo)
    {
        $hasUser = Db::name($this->table)
            ->where('wechat_openid', Arr::get($userInfo, 'openid'))
            ->where('wechat_unionid', Arr::get($userInfo, 'unionid'))
            ->find() ?: [];
        $userId = 0;
        try {
            Db::startTrans();
            if ($hasUser) {
                //更新
                $updateData = [
                    'avatar'            => Arr::get($userInfo, 'headimgurl'),
                    'wechat_nickname'   => Arr::get($userInfo, 'nickname'),
                    'is_subscribe'      => 1,
                    'login_num'         => Db::raw('login_num+1'),
                    'login_time'        => time(),
                    'last_login_time'   => Arr::get($hasUser, 'login_time'),
                    'login_ip'          => app()->request->ip(),
                    'last_login_ip'     => Arr::get($hasUser, 'login_ip'),
                    'updated_at'        => time(),
                ];
                Db::name($this->table)->where('id', Arr::get($hasUser, 'id'))
                    ->update($updateData);
                $userId = Arr::get($hasUser, 'id');
            } else {
                //新增
                $insertData = [
                    'name'              => Arr::get($userInfo, 'nickname'),
                    'password'          => password_hash('xuexiao123', PASSWORD_DEFAULT),
                    'avatar'            => Arr::get($userInfo, 'headimgurl'),
                    'sex'               => Arr::get($userInfo, 'sex'),
                    'wechat_nickname'   => Arr::get($userInfo, 'nickname'),
                    'wechat_unionid'    => Arr::get($userInfo, 'unionid', ''),
                    'wechat_openid'     => Arr::get($userInfo, 'openid'),
                    'areainfo'          => Arr::get($userInfo, 'province') . ' ' . Arr::get($userInfo, 'city'),
                    'is_subscribe'      => 1,
                    'is_deleted'        => 0,
                    'login_num'         => 1,
                    'login_time'        => time(),
                    'last_login_time'   => time(),
                    'login_ip'          => app()->request->ip(),
                    'last_login_ip'     => app()->request->ip(),
                    'created_at'        => time(),
                    'updated_at'        => time(),
                ];
                $userId = Db::name($this->table)->insertGetId($insertData);
                $this->__initUser($userId);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
        return Db::name($this->table)
            ->where('id', $userId)
            ->field('last_login_ip,login_ip,password', true)
            ->find() ?: [];
    }


    /**
     * 初始化用户基本信息
     * @param $userId
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function __initUser($userId)
    {
        //1: 用户扩展表
        Data::save(
            'user_extend',
            [
                'user_id'               => $userId,
                'true_name'             => '',
                'credit_score'          => 100,
                'publish_job_num'       => 0,
                'join_job_num'          => '',
            ]
        );
        //2: 用户公司扩展表
        Data::save(
            'user_extend_bus',
            [
                'user_id'               => $userId,
            ]
        );
        //3： 送发布豆
        Data::save(
            'user_wallet',
            [
                'user_id'           => $userId,
                'publish_bean'      => sysconf('register_system_bean') ?: 0,
            ]
        );
        //发布豆流水记录
        if ((sysconf('register_system_bean') ?: 0)) {
            Data::save(
                'user_recharge_log',
                [
                    'user_id'           => $userId,
                    'recharge_money'    => 0,
                    'publish_bean'      => sysconf('register_system_bean') ?: 0,
                    'recharge_rate'     => 0,
                    'give_publish_bean' => 0,
                    'give_rate'         => 0,
                    'type'              => 1,
                    'kind'              => 3
                ]
            );
        }
    }


    /**
     * 监测用户信息是否补充完成
     * @param $userInfo
     *
     * @return bool
     */
    public function checkUserInfoIsDone($userInfo)
    {
        if (Arr::get($userInfo, 'type') && Arr::valueEq($userInfo, 'status', 2)) {
            return true;
        }
        return false;
    }


    /**
     * 用户收藏
     * @param $collectId
     * @param $userId
     * @param $type
     *
     * @return bool
     * @throws \think\Exception
     */
    public function userCollect($collectId, $userId, $type)
    {
        Db::name('user_collect')
            ->insertGetId([
                'user_id'       => $userId,
                'collect_id'    => $collectId,
                'type'          => $type,
                'created_at'    => time(),
                'updated_at'    => time()
            ]);
        if ($type == 1) {
            Db::name('jobs')
                ->where('id', $collectId)
                ->setInc('collect_num');
        }
        if ($type == 2) {
            Db::name('market')
                ->where('id', $collectId)
                ->setInc('collect_num');
        }
        return true;
    }


    /**
     * 用户取消收藏
     * @param $collectId
     * @param $userId
     * @param $type
     *
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function userDelCollect($collectId, $userId, $type)
    {
        Db::name('user_collect')
            ->where('collect_id', $collectId)
            ->where('user_id', $userId)
            ->where('type', $type)
            ->delete();
        if ($type == 1) {
            Db::name('jobs')
                ->where('id', $collectId)
                ->setDec('collect_num');
        }
        if ($type == 2) {
            Db::name('market')
                ->where('id', $collectId)
                ->setDec('collect_num');
        }
        return true;
    }



    /**
     * 检测用户是否已经收藏该项目
     * @param $collectId
     * @param $userId
     * @param $type 1:兼职 2：二手商品
     *
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isCollect($collectId, $userId, $type)
    {
        return Db::name('user_collect')
            ->where('user_id', $userId)
            ->where('type', $type)
            ->where('collect_id', $collectId)
            ->find() ? true : false;
    }


    /**
     * 用户认证成 个人 用户
     * @param $postData
     *
     * @return bool|int|string
     * @throws \Exception
     */
    public function submitApprovePerson($postData)
    {
        $result = false;
        try {
            Db::startTrans();
            //1: 更新  user_extend
            $result = Db::name('user_extend')
                ->where('user_id', Arr::get($postData, 'user_id'))
                ->update([
                    'true_name'         => Arr::get($postData, 'true_name', ''),
                    'true_sex'          => Arr::get($postData, 'true_sex', 0),
                    'true_age'          => Arr::get($postData, 'true_age', ''),
                    /*'id_card'           => Arr::get($postData, 'id_card', ''),*/
                    'mobile'            => Arr::get($postData, 'mobile', ''),
                    'profession'        => Arr::get($postData, 'profession', 10),
                    /*'id_card_zm_img'    => Arr::get($postData, 'id_card_zm_img', ''),
                    'id_card_bm_img'    => Arr::get($postData, 'id_card_bm_img', ''),*/
                    'wechat_id_card'    => Arr::get($postData, 'wechat_id_card', ''),
                    'qq_num'            => Arr::get($postData, 'qq_num', ''),
                    'alipay_num'            => Arr::get($postData, 'alipay_num', ''),
                    'education_class'   => Arr::get($postData, 'education_class', 9),
                    'education_school'  => Arr::get($postData, 'education_school', 0),
                    'education_major'   => Arr::get($postData, 'education_major', 0),
                    'updated_at'        => time()
                ]);

            //2: 更新 user
            if ($result) {
                $userUpdateData = [
                    'truename'          => Arr::get($postData, 'true_name', ''),
                    'sex'               => Arr::get($postData, 'true_sex', 0),
                    'email'             => Arr::get($postData, 'email', ''),
                    'mobile'            => Arr::get($postData, 'mobile', ''),
                    'provinceid'        => Arr::get($postData, 'provinceid', 0),
                    'cityid'            => Arr::get($postData, 'cityid', 0),
                    'areaid'            => Arr::get($postData, 'areaid', 0),
                    'areainfo'          => Arr::get($postData, 'areainfo', ''),
                    'type'              => Arr::get($postData, 'type', 1),
                    'status'            => 1,
                    'updated_at'        => time()
                ];
                if (Arr::get($postData, 'email', 0)) {
                    $userUpdateData['email_bind'] = 1;
                }
                if (Arr::get($postData, 'mobile', 0)) {
                    $userUpdateData['mobile_bind'] = 1;
                }
                $result = Db::name('user')
                    ->where('id', Arr::get($postData, 'user_id'))
                    ->update($userUpdateData);
                if ($result) {
                    Db::commit();
                    //通知代理商审核
                    (new UserTemplateService())->sendApprovePerson($postData);
                    (new UserTemplateService())->approveKefu($postData);
                } else {
                    throw new \Exception('更新 user 失败！');
                }
            } else {
                throw new \Exception('更新user_extend 失败!');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
        return $result;
    }



    /**
     * 用户认证成 企业 用户
     * @param $postData
     *
     * @return bool|int|string
     * @throws \Exception
     */
    public function submitApproveCompany($postData)
    {
        $result = false;
        try {
            Db::startTrans();
            //1: 更新  user_extend
            $result = Db::name('user_extend')
                ->where('user_id', Arr::get($postData, 'user_id', 0))
                ->update([
                    'true_name'         => Arr::get($postData, 'legal_person_name', ''),
                    'id_card'           => Arr::get($postData, 'legal_person_id_card', ''),
                    'mobile'            => Arr::get($postData, 'company_mobile', ''),
                    'id_card_zm_img'    => Arr::get($postData, 'id_card_zm_img', ''),
                    'id_card_bm_img'    => Arr::get($postData, 'id_card_bm_img', ''),
                    'profession'        => 11,
                    'updated_at'        => time()
                ]);
            
            //2: 更新 user_extend_bus
            if ($result) {
                $result = Db::name('user_extend_bus')
                    ->where('user_id', Arr::get($postData, 'user_id', 0))
                    ->update([
                        'company_name'              => Arr::get($postData, 'company_name'),
                        'company_logo'              => Arr::get($postData, 'company_logo'),
                        'company_intro'             => mb_substr(Arr::get($postData, 'company_intro', ''), 0, 100),
                        'company_address'           => Arr::get($postData, 'areainfo'),
                        'legal_person_name'         => Arr::get($postData, 'legal_person_name'),
                        'company_mobile'            => Arr::get($postData, 'company_mobile'),
                        'legal_person_id_card'      => Arr::get($postData, 'legal_person_id_card'),
                        'id_card_zm_img'            => Arr::get($postData, 'id_card_zm_img'),
                        'id_card_bm_img'            => Arr::get($postData, 'id_card_bm_img'),
                        'company_license'           => Arr::get($postData, 'company_license'),
                        'company_license_img'       => Arr::get($postData, 'company_license_img'),
                        'updated_at'                => time()
                    ]);
                if (!$result) {
                    throw new \Exception('更新 user_extend_bus失败！');
                }
                
            }

            //3: 更新 user
            if ($result) {
                $userUpdateData = [
                    'truename'          => Arr::get($postData, 'legal_person_name', ''),
                    'email'             => Arr::get($postData, 'email', ''),
                    'mobile'            => Arr::get($postData, 'company_mobile', ''),
                    'provinceid'        => Arr::get($postData, 'provinceid', 0),
                    'cityid'            => Arr::get($postData, 'cityid', 0),
                    'areaid'            => Arr::get($postData, 'areaid', 0),
                    'areainfo'          => Arr::get($postData, 'areainfo', ''),
                    'type'              => Arr::get($postData, 'type', 2),
                    'status'            => 1,
                    'updated_at'        => time()
                ];
                if (Arr::get($postData, 'email', 0)) {
                    $userUpdateData['email_bind'] = 1;
                }
                if (Arr::get($postData, 'company_mobile', 0)) {
                    $userUpdateData['mobile_bind'] = 1;
                }
                $result = Db::name('user')
                    ->where('id', Arr::get($postData, 'user_id'))
                    ->update($userUpdateData);
                if ($result) {
                    Db::commit();
                    //通知代理商审核
                    (new UserTemplateService())->sendApproveCompany($postData);
                    (new UserTemplateService())->approveKefu($postData);
                } else {
                    throw new \Exception('更新 user 失败！');
                }
            } else {
                throw new \Exception('更新user_extend 失败!');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
        return $result;
    }






}
